package com.life.notes.config.exception;

import com.life.notes.config.constant.ResultEnum;
import com.life.notes.config.utils.BaseResponse;
import com.life.notes.config.utils.ResponseMsgUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ValidationException;

/**
 * @author lishuqian
 * @date 2020/6/15
 */
@ControllerAdvice
public class GlobalExceptionConfig {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionConfig.class);

    public GlobalExceptionConfig() {
    }

    @ExceptionHandler({SystemException.class})
    @ResponseBody
    public BaseResponse handle(SystemException systemException) {
        log.error(String.valueOf(systemException));
        return systemException.getCode() == null ? ResponseMsgUtil.error(900, systemException.getMsg()) : ResponseMsgUtil.error(systemException.getCode(), systemException.getMsg());
    }
    @ExceptionHandler({ValidationException.class})
    @ResponseBody
    public BaseResponse handle(ValidationException systemException) {
        log.error(String.valueOf(systemException));
        return ResponseMsgUtil.error(900, systemException.getCause().getMessage());
    }

    /**
     * UserAuthAccessDeniedHandler不生效是因为被Exception拦截了，所以要自定义
     * @param accessDeniedException
     * @return
     */
    @ExceptionHandler({AccessDeniedException.class})
    @ResponseBody
    public BaseResponse handle(AccessDeniedException accessDeniedException) {
        log.error(String.valueOf(accessDeniedException));
        return ResponseMsgUtil.error(403,"未授权");
    }

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public BaseResponse defaultExceptionHandler(Exception e) {
        log.error("系统异常!", e);
        return ResponseMsgUtil.error(ResultEnum.SYSTEM_ERROR.getMessage());
    }
}
